package cn.shengongying.utils;

import cn.shengongying.exception.BusinessException;
import cn.shengongying.exception.DigestException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

/**
 * author: RXK
 * date: 2022/1/6 星期四
 * desc:
 */
public class GeTuiUtils {

    private GeTuiUtils() {
    }


    private static final String APP_ID = "nV49GP2NAg8edcrMpHsLG8";
    private static final String APP_KEY = "qSYZslbYXM7IfwwfvCnk4";
    private static final String APP_SECRET = "m4REBgOrZ29Y7GvfCYowN7";
    private static final String MASTER_SECRET = "dhEY5nhBiJ8oWA6Zq88Te2";
    //手机号码一键登录
    private static final String gy_get_pn = "https://openapi-gy.getui.com/v2/gy/ct_login/gy_get_pn";

    public static String gy_get_pn(String token, String gyuid) throws DigestException, BusinessException {
        String pn = getPn(token, gyuid);
        return AesUtils.geTuiDecrypt(pn, MASTER_SECRET);
    }

    /**
     * https://docs.getui.com/geyan/server/
     * 返回的结果实例：
     * {
     *     "errno": "0",
     *     "data": {
     *         "result": "20000",
     *         "msg": "成功",
     *         "data": {
     *             "pn": "1fbf2605f954fad3ba18115000735aee",
     *         }
     *     }
     * }
     * @throws DigestException ：加解密异常
     * @throws BusinessException ：业务交互异常
     */
    private static String getPn(String token, String gyuid) throws DigestException, BusinessException {
        long timestamp = System.currentTimeMillis();
        JSONObject params = new JSONObject();
        params.put("appId", APP_ID);
        params.put("timestamp", timestamp);
        params.put("sign", SignUtils.sha256(APP_KEY+timestamp+MASTER_SECRET));
        params.put("token", token);
        params.put("gyuid", gyuid);
        String result = HttpUtils.postJson(params.toString(),gy_get_pn);
        if (StringUtils.isEmpty(result)) {
            throw new BusinessException("请求个推返回结果为空");
        }
        JSONObject parse = JSONObject.parseObject(result);
        JSONObject data = parse.getJSONObject("data");
        String code = data.getString("result");
        if ("2000".equals(code)) {
            return data.getJSONObject("data")
                    .getString("pn");
        }
        throw new BusinessException("请求个推返回错误结果：{" + result + "}");
    }
}
